package com.nlp.visualization.core.discourse.impl;

import com.hankcs.hanlp.corpus.io.IOUtil;
import com.hankcs.hanlp.mining.word2vec.DocVectorModel;
import com.hankcs.hanlp.mining.word2vec.Word2VecTrainer;
import com.hankcs.hanlp.mining.word2vec.WordVectorModel;
import com.nlp.visualization.core.discourse.IWord2VecService;
import com.nlp.visualization.utils.PropertyUtil;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;

/**
 * @author LXM
 * @Title:
 * @Description: 词向量的实现模块
 * @date 2018/2/25下午4:33
 */
@Service
public class Word2VecServiceImpl implements IWord2VecService {

    static Logger logger = LoggerFactory.getLogger(Word2VecServiceImpl.class);
    //    private static final String TRAIN_FILE_NAME = PropertyUtil.getInstance("hanlp").getProperty("train_vec_file");
    private static final String MODEL_FILE_NAME = PropertyUtil.getInstance("hanlp").getProperty("root") + PropertyUtil.getInstance("hanlp").getProperty("vector_model");

    private static volatile WordVectorModel model = null;

//    /**
//     * 训练并载入模型
//     *
//     * @return
//     * @throws IOException
//     */
//    static WordVectorModel trainOrLoadModel() throws IOException {
//        if (!IOUtil.isFileExisted(MODEL_FILE_NAME)) {
//            if (!IOUtil.isFileExisted(TRAIN_FILE_NAME)) {
//                logger.info("语料不存在，请阅读文档了解语料获取与格式");
//            }
//            Word2VecTrainer trainerBuilder = new Word2VecTrainer();
//            return trainerBuilder.train(TRAIN_FILE_NAME, MODEL_FILE_NAME);
//        }
//
//        return loadModel();
//    }


    /**
     * 单单载入模型
     *
     * @return
     * @throws IOException
     */
    public static WordVectorModel loadModel() {
        if (model == null) {
            synchronized (WordVectorModel.class) {
                if (model == null) {
                    try {
                        model = new WordVectorModel(MODEL_FILE_NAME);
                    } catch (IOException e) {
                        logger.error("载入词向量模型异常");
                        e.printStackTrace();
                    }
                }
            }
        }
        return model;
    }


    @Override
    public float similarCompare(String what, String with) {
        //词向量
        WordVectorModel wordVectorModel = loadModel();
        // 文档向量
        DocVectorModel docVectorModel = new DocVectorModel(wordVectorModel);

        return docVectorModel.similarity(what, with);
    }
}
